package com.xhgj.thread;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author 周宇
 * @create 2020-06-27 12:28
 * 创建线程方式3 改造下载图片案例
 */
//1、实现Callable接口，需要返回值类
public class PrimeCallable implements Callable<Boolean> {

    private String url;//图片地址
    private String name;//保存的图片名

    public PrimeCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    //2、重写call方法，需要抛出异常
    @Override
    public Boolean call() throws Exception {
        Boolean bool;
        WebDownloader2 webDownloader = new WebDownloader2();
        bool = webDownloader.downloader(url, name);
        System.out.println("下载了文件名为：" + name);
        return bool;
    }

    public static void main(String[] args) throws Exception {
        //3、创建目标对象
        PrimeCallable p1 = new PrimeCallable("https://cdn2.jianshu.io/assets/default_avatar/2-9636b13945b9ccf345bc98d0d81074eb.jpg", "1.jpg");
        PrimeCallable p2 = new PrimeCallable("http://seopic.699pic.com/photo/50163/5313.jpg_wh1200.jpg", "2.jpg");
        PrimeCallable p3 = new PrimeCallable("https://highpic.originoo.com/highpic/detail/161025/RM/bji81201635.jpg", "3.jpg");
        //4、创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //5、提交执行
        Future<Boolean> result1 = ser.submit(p1);
        Future<Boolean> result2 = ser.submit(p2);
        Future<Boolean> result3 = ser.submit(p3);
        //6、获取结果
        Boolean r1 = result1.get();
        Boolean r2 = result2.get();
        Boolean r3 = result3.get();
        //7、关闭服务
        ser.shutdownNow();
        System.out.println("r1:" + r1 + "\tr2:" + r2 + "\tr3:" + r3);
    }
}

//下载器
class WebDownloader2 {
    //下载方法
    public boolean downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
            return false;
        }
        return true;
    }
}